package io.renren.modules.message.email;

import com.alibaba.druid.util.StringUtils;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/*** 用465端口发送邮件** @author qiaojun* @date 2019/8/12*/
public class AliMailUtils {

    private static String USER_NAME = "fii_cc@163.com";//发件人
    private static String PASSWORD = "JDEJCRXFQEXXZAGV";//密码
    private static String HOST = "smtp.163.com";

    public static void main(String[] args) {
        sendMail("15953295779@126.com", null, "测试标题", "测试内容");
    }

    public static void sendMail(String subject, String content) {
        sendMail(null, null, subject, "content");
    }

    public static void sendMail(String to, String subject, String content) {
        sendMail(to, null, subject, "content");
    }

    /*** 发邮件端口改为465** @param to      发送人 逗号分开* @param cc      抄送人 逗号分开* @param content 发送内容*/
    public static void sendMail(String to, String cc, String subject, String content) {
        if (null == to) {
            return;
        }
        Properties props = new Properties();
        props.put("username", USER_NAME);
        props.put("password", PASSWORD);//网易的smtp服务器地址
        props.put("mail.smtp.host", HOST);//SSLSocketFactory类的端口
        props.put("mail.smtp.socketFactory.port", "465");//SSLSocketFactory类
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");//网易提供的ssl加密端口,QQ邮箱也是该端口
        props.put("mail.smtp.port", "465");
        Session defaultInstance = Session.getDefaultInstance(props);
        try {
            Session session = Session.getInstance(props, null);
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(props.getProperty("username")));
            if (StringUtils.isEmpty(to)) {
                to = "xxxxsfdsf@163.com";
            }
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            if (cc != null) {
                message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc));
            }
            message.setSubject(subject);// 正文和响应头
            message.setContent(content, "text/html;charset=UTF-8");
            message.saveChanges();
            Transport transport = defaultInstance.getTransport("smtp");
            transport.connect(props.getProperty("mail.smtp.host"), props.getProperty("username"), props.getProperty("password"));
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

}
